-- UIWorkshopStore
-- Create by zouyb
-- 材料仓库界面

require "game/ui/form/workshop/UIItemDesc"

--UIWorkshopStore继承自Layer
UIWorkshopStore = class("UIWorkshopStore", function()
    return cc.Layer:create();
end);

function UIWorkshopStore.create()
    return UIWorkshopStore.new();
end

local resize;

local MAX_TAB_NUM = 6;
local OTHER_GROUP = 1;
local relic_puzzlebox = {1511, 1512, 6000, 6010, 6020};

-- 符石排序顺序
local stoneSortOrder = {["revenge"] = 1, ["explore"] = 2, ["plunder"] = 3};

-- 按星级排序
function sortByStar(item1, item2)
    local rank1 = ItemM.query(item1, "rank");
    local rank2 = ItemM.query(item2, "rank");
    if rank1 < rank2 then
        return true;
    else
        return false;
    end
end

-- 按冈布奥排序(按照ITEMID排序即可)
function sortBySlime(item1, item2)
    if item1 < item2 then
        return true;
    else
        return false;
    end
end

-- 按优先优先级排序
function sortByPriority(item1, item2)
    local priority1 = tonumber(ItemM.query(item1, "sort_priority"));
    local priority2 = tonumber(ItemM.query(item2, "sort_priority"));

    -- 先按优先级排
    if priority1 < priority2 then
        return true;
    elseif priority1 > priority2 then
        return false;
    end

    -- 符石排列需要根据对应的类型,检查下符石
    local style1 = SkyStoneM.query(item1, "style");
    local style2 = SkyStoneM.query(item2, "style");
    if style1 and style2 then
        local order1 = tonumber(stoneSortOrder[style1]);
        local order2 = tonumber(stoneSortOrder[style2]);

        if order1 < order2 then
            return true;
        elseif order1 > order2 then
            return false;
        end
    end

    local rank1 = ItemM.query(item1, "rank");
    local rank2 = ItemM.query(item2, "rank");

    if rank1 < rank2 then
        return true;
    elseif rank1 > rank2 then
        return false;
    end

    -- 按id排序
    return item1 < item2;
end

-- 页签列表        食材，       炼金材料，      冈布奥碎片，       其他（罐，遗物）， 天空之城物资，           药剂
-- 对应Item表中的group
local groupList = { {20},       {15},           {17},              {OTHER_GROUP},     {30},                    {27} };
-- 排序方法
local sortList =  { sortByStar, sortByStar,     sortBySlime,       sortByStar,        sortByPriority,              sortByStar }
-- 标题名称
local nameList = { "tab_food",  "tab_material", "tab_honor_piece", "tab_others",      "tab_sky_city_resource", "tab_bottle" };
-- 标题背景
local bgTypeList = { "food",    "alchemy",      "pet",             "pet",             "airship",               "pet" };
-- 标签图标
local tabImgList = { 1204,      1006,           2001,              1511,              10000,                   9000 };

--构造函数
function UIWorkshopStore:ctor()
    self:setName("UIWorkshopStore");

    --初始化
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopStore.csb");
    self:addChild(node);
    self.node = node;

    local scrollview = findChildByName(self.node, "CT/scrollview");
    self.initHeight = scrollview:getInnerContainerSize().height;

    -- 默认选中页签1
    self:initTabs();
    self:selectTab(self.tabList[1]:getTag());

    self:init();

    local titleLabel = findChildByName(self.node, "CT/title");
    local subHeadLabel = findChildByName(self.node, "CT/subhead");
    TextStyleM.setTitleStyle(titleLabel);
    TextStyleM.setSubheadStyle(subHeadLabel);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIWorkshopStore");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册工坊信息更新的回调
    EventMgr.register("UIWorkshopStore", event.ITEM_COUNT_UPDATED, function(classId)
        self:updateItemCount(classId);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIWorkshopStore", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIWorkshopStore" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            -- 窗口关闭，清除工坊信息更新的回调
            EventMgr.removeAll("UIWorkshopStore");

            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:showBottomMenu();
            end
        elseif ev == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:hideBottomMenu();
            end

            -- 播放界面音效
            AudioM.playFx("workshop_store");
        end
    end);

    resize(self);
end

-- 初始化页签
function UIWorkshopStore:initTabs()
    self.tabList = {};

    local startY = 0;
    local gap = 100;
    -- local tab6 = findChildByName(self.node, "CT/tab"..6);
    -- tab6:setVisible(false);

    for i = 1, MAX_TAB_NUM do
        local tab = findChildByName(self.node, "CT/tab"..i);
        tab:setTag(i);
        local tabIcon = findChildByName(tab, "tab_icon");
        tabIcon:loadTexture(getItemIconPath(tabImgList[i]));
        tabIcon:setScale(0.6);

        if startY == 0 and i == 1 then
            startY = tab:getPositionY();
        end

        local items = {};
        local groups = groupList[i];
        for i = 1, #groups do
            -- group == 1特殊物品特殊显示，暂时只显示罐子和遗物
            if groups[i] == OTHER_GROUP then
                local ret = {};
                for _, classId in pairs(relic_puzzlebox) do

                    if ItemM.getAmount2(ME.user, classId) > 0 then
                        table.insert(ret, classId);
                    end
                end
                items = table.append(items, ret);
            else
                items = table.append(items, ItemM.getItemsByGroup2(ME.user, groups[i]));
            end
        end

        if #items > 0 then
            table.insert(self.tabList, tab);
            tab:setVisible(true);
        else
            tab:setVisible(false);
        end

        tab:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_bag");
                -- 选中页签处理
                self:selectTab(sender:getTag());
                self:init();
            end
        end);
    end

    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        tab:setPositionY(startY - (i - 1) * gap);
    end
end

-- 改变页签状态
function UIWorkshopStore:selectTab(index)
    self.selectIndex = index;

    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        if index == tab:getTag() then
            tab:setColor(normalColor);
        else
            tab:setColor(blendColor);
        end
    end

    -- 标题
    local titleLabel = findChildByName(self.node, "CT/title");
    local subHeadLabel = findChildByName(self.node, "CT/subhead");
    titleLabel:setString(getLocStr("store_title"));
    subHeadLabel:setString(getLocStr(nameList[index]));

    --标题背景
    local btTypeImg = findChildByName(self.node, "CT/bg_type");
    local btTypeImg2 = findChildByName(self.node, "CT/bg_type2");

    btTypeImg:loadTexture(getTitleBgIconPath(bgTypeList[index]));
    btTypeImg2:loadTexture(getTitleBgIconPath(bgTypeList[index]));
end

-- 初始化道具
function UIWorkshopStore:initItem(node, classId)
    -- 图标
    local icon = findChildByName(node, "icon");
    local iconPath = getItemIconPath(ItemM.query(classId, "icon"));
    icon:loadTexture(iconPath);

    -- 数量
    local numLabel = findChildByName(node, "num");
    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
    numLabel:setString(ItemM.getAmount2(ME.user, classId));

    -- 点击处理
    local bg = findChildByName(node, "bg");
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("workshop_material");

            if ArtifactM.isArtifact(classId) then
                -- 如果是神器，显示神器信息
                showEquipTooltip(classId);
            else
                -- 显示道具详细信息
                if 27 == ItemM.query(classId, "group") then
                    local uiItemDesc = UIItemDesc.create(classId, true);
                    UIMgr:getCurrentScene():addForm(uiItemDesc);
                else
                    local uiItemDesc = UIItemDesc.create(classId);
                    UIMgr:getCurrentScene():addForm(uiItemDesc);
                end
            end
        end
    end);
end

-- 初始化道具列表
function UIWorkshopStore:init()
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/workshop/StoreItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    local numPerRow = 3;

    local items = {};
    local groups = groupList[self.selectIndex];
    for i = 1, #groups do
        items = table.append(items, ItemM.getItemsByGroup2(ME.user, groups[i]));
    end

    table.sort(items, sortList[self.selectIndex]);

    -- 图标间距
    local  hGap = 15;
    local  wGap = 15;
    -- 图标宽度
    local iconWidth = 135;
    local itemNum = #items;

    -- 先计算总高度
    local totalHeight = math.max((math.ceil(itemNum / numPerRow)) * iconWidth + 30, self.initHeight);
    local areaWidth = scrollview:getContentSize().width;

    wGap = (areaWidth - iconWidth * numPerRow) / (numPerRow + 1);

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    self.itemIcons = {};
    for i = 1, itemNum do
        local child = widget:clone();
        local x = (((i-1) % numPerRow))*(iconWidth + wGap) + iconWidth/2 + wGap;
        local y = totalHeight - math.floor((i-1) / numPerRow) * (iconWidth) - (iconWidth/2+hGap);
        child:setPositionX(x);
        child:setPositionY(y);

        -- 初始化道具
        child:setTag(items[i]);
        self:initItem(child, items[i]);

        scrollview:addChild(child);
        table.insert(self.itemIcons, child);
    end

    -- 默认滑到最顶端
    scrollToTop(scrollview);
end

-- 更新道具数量
function UIWorkshopStore:updateItemCount(classId)
    local group = ItemM.query(classId, "group");
    -- 屑、砂之类的道具不显示
    if group == 14 then
        return;
    end

    -- 该道具是否需要显示在当前选中页签里
    local groups = groupList[self.selectIndex];
    if table.indexOf(groups, group) == -1 then
        return;
    end

    if self.updateTickNode == nil then
        self.updateTickNode = cc.Node:create();
        self:addChild(self.updateTickNode);
    end

    local function delayInit()
        if ItemM.getAmount2(ME.user, classId) == 0 then
            -- 数量为0， 重新初始化
            self:init();
            return;
        end

        local found = false;
        for i = 1, #self.itemIcons do
            local itemNode = self.itemIcons[i];
            local itemId = itemNode:getTag();

            -- 更新数量
            if itemId == classId then
                local numLabel = findChildByName(itemNode, "num");
                numLabel:setString(ItemM.getAmount2(ME.user, classId));
                found = true;
                break;
            end
        end

        if not found then
            -- 新增的道具，也需要 重新初始化
            self:init();
            return;
        end
    end

    -- 当收到服务器多条MSG_ITEM时，此处做下延迟，防止多次重复初始化
    self.updateTickNode:stopAllActions();
    performWithDelay(self.updateTickNode, delayInit, 0.1);
end

resize = function(self)
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


